﻿using CompanyManageSystem.DLL;
using CompanyManageSystem.Model;
using CompanyManageSystem.Service;
using DevExpress.XtraReports;
using gregn6Lib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CompanyManageSystem.UI.Info
{
    public partial class Frm_Staff : BaseXtraForm
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        public Frm_Staff()
        {
            InitializeComponent();

            #region TreeList属性
            CompanyTree.LookAndFeel.UseWindowsXPTheme = true;
            CompanyTree.LookAndFeel.UseDefaultLookAndFeel = false;
            CompanyTree.Appearance.FocusedCell.BackColor = Color.LightSteelBlue;
            CompanyTree.Appearance.FocusedCell.BackColor2 = Color.SteelBlue;
            CompanyTree.OptionsView.ShowHorzLines = false;
            CompanyTree.OptionsView.ShowVertLines = false;
            CompanyTree.OptionsView.FocusRectStyle = DevExpress.XtraTreeList.DrawFocusRectStyle.None;

            DeptTree.Appearance.FocusedCell.BackColor = Color.LightSteelBlue;
            DeptTree.Appearance.FocusedCell.BackColor2 = Color.SteelBlue;
            DeptTree.OptionsView.ShowHorzLines = false;
            DeptTree.OptionsView.ShowVertLines = false;
            DeptTree.OptionsView.FocusRectStyle = DevExpress.XtraTreeList.DrawFocusRectStyle.None;
            #endregion

            AppService aservice = new AppService();
            CompanyTree.DataSource = aservice.GetCompanys();

            this.BindCheckEdit(StaffView, false, false);
            this.CustomDrawNodeButton(DeptTree);
            this.CustomDrawNodeImages(DeptTree);
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Staff_Load(object sender, EventArgs e)
        {
           
        }

        #region 公司
        /// <summary>
        /// 增加公司
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CompanyTree.Nodes.Count <= 0)
            {
                Frm_AddCompany frm = new Frm_AddCompany(status: EStatus.Add);
                frm.SaveEvent += company_AddSaveEvent;
                frm.ShowDialog();
            }
            else
            {
                var companyID = CompanyTree.FocusedNode.GetValue("ID");

                Frm_AddCompany frm = new Frm_AddCompany(id: (Guid)companyID, status: EStatus.Add);
                frm.SaveEvent += company_AddSaveEvent;
                frm.ShowDialog();
            }

        }
        private void company_AddSaveEvent(Object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            CompanyTree.DataSource = aservice.GetCompanys();
        }

        /// <summary>
        /// 编辑公司
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var companyID = CompanyTree.FocusedNode.GetValue("ID");
            if (CompanyTree.FocusedNode.Level == 0)
            {
                MessageBox.Show("首层无法编辑公司!");
                return;
            }
            Frm_AddCompany frm = new Frm_AddCompany(id: (Guid)companyID, status: EStatus.Modify);
            frm.SaveEvent += company_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void company_UpdateSaveEvent(Object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            Company com = sender as Company;
            var node = CompanyTree.FocusedNode;
            if (com != null)
            {
                node["CName"] = com.CName;
                //DeptTree.DataSource = aservice.GetDeptByCompanyID(com.ID);
            }
            else
            {
                aservice = new AppService();
                CompanyTree.DataSource = aservice.GetCompanys();
            }

        }

        /// <summary>
        /// 删除公司
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("确定删除公司?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                AppService aservice = new AppService();
                var companyID = CompanyTree.FocusedNode.GetValue("ID");
                aservice.DelCompany((Guid)companyID, CompanyTree.FocusedNode);
                CompanyTree.DeleteNode(CompanyTree.FocusedNode);
            }
        }

        /// <summary>
        /// 公司右键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CompanyTree_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                popupMenu1.ShowPopup(Control.MousePosition);
            }
        }

        /// <summary>
        /// 公司焦点行改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CompanyTree_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            AppService aservice = new AppService();
            var companyID = CompanyTree.FocusedNode.GetValue("ID");
            DeptTree.DataSource = aservice.GetDeptByCompanyID((Guid)companyID);
            if (DeptTree.Nodes.Count <= 0)
            {
                StaffGrid.DataSource = null;
            }
        }
        #endregion

        #region 部门
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var companyID = CompanyTree.FocusedNode.GetValue("ID");
            if (DeptTree.Nodes.Count == 0)
            {
                Frm_AddDepartment frm = new Frm_AddDepartment(status: EStatus.Add, companyID: (Guid)companyID, parentID: null);
                frm.SaveEvent += Department_AddSaveEvent;
                frm.ShowDialog();
            }
            else
            {
                //获取焦点行公司ID和部门ID
                var deptID = DeptTree.FocusedNode.GetValue("ID");

                Frm_AddDepartment frm = new Frm_AddDepartment(status: EStatus.Add, companyID: (Guid)companyID, parentID: (Guid)deptID);
                frm.SaveEvent += Department_AddSaveEvent;
                frm.ShowDialog();
            }
        }
        private void Department_AddSaveEvent(object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            var companyID = CompanyTree.FocusedNode.GetValue("ID");
            //Department dept = sender as Department;
            //var focusNode = treeList1.FocusedNode;
            //var parentNode = focusNode.ParentNode;
            DeptTree.DataSource = aservice.GetDeptByCompanyID((Guid)companyID);
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var id = DeptTree.FocusedNode.GetValue("ID");
            Frm_AddDepartment frm = new Frm_AddDepartment(status: EStatus.Modify, deptID: (Guid)id);
            frm.SaveEvent += Department_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void Department_UpdateSaveEvent(object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            Department dept = sender as Department;
            var deptID = DeptTree.FocusedNode.GetValue("ID");
            var node = DeptTree.FocusedNode;
            //更改节点文字
            node["Code"] = dept.Code;
            node["Name"] = dept.Name;
            //repositoryItemSearchLookUpEdit1.DataSource = aservice.GetDepartments();
            //StaffGrid.DataSource = aservice.GetUserByDepartmentID((Guid)deptID);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem9_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppService aservice = new AppService();
            var node = DeptTree.FocusedNode;
            var id = DeptTree.FocusedNode.GetValue("ID");
            var name = DeptTree.FocusedNode.GetValue("Name");

            if (DialogResult.OK == MessageBox.Show($"是否删除【{name}】嘛?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                //确定
                aservice.DelDept((Guid)id, node);
                DeptTree.DeleteNode(node);
                ShowInfo("删除部门成功!");
            }
        }

        /// <summary>
        /// 部门右键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeptTree_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                popupMenu2.ShowPopup(Control.MousePosition);
            }
        }

        /// <summary>
        /// 部门焦点行改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeptTree_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            AppService aservice = new AppService();
            var deptID = DeptTree.FocusedNode.GetValue("ID");
            StaffGrid.DataSource = aservice.GetStaffByDeptID((Guid)deptID);
            repositoryItemSearchLookUpEdit1.DataSource = aservice.GetDepartments();
            repositoryItemSearchLookUpEdit2.DataSource = aservice.GetAllProvinces();

        }
        #endregion

        #region 员工
        /// <summary>
        /// 添加员工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DeptTree.Nodes.Count == 0)
            {
                MessageBox.Show("请选择部门!");
                return;
            }

            var companyID = CompanyTree.FocusedNode.GetValue("ID");
            var deptID = DeptTree.FocusedNode.GetValue("ID");

            Frm_AddStaff frm = new Frm_AddStaff(companyID: (Guid)companyID, deptID: (Guid)deptID, status: EStatus.Add);
            frm.SaveEvent += Staff_AddSaveEvent;
            frm.ShowDialog();
        }
        private void Staff_AddSaveEvent(Object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            var deptID = DeptTree.FocusedNode.GetValue("ID");
            StaffGrid.DataSource = aservice.GetStaffByDeptID((Guid)deptID);
        }

        /// <summary>
        /// 编辑员工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CompanyStaffInfo staff = StaffView.GetFocusedRow() as CompanyStaffInfo;

            if (staff == null)
            {
                ShowInfo("请选择需要编辑的员工!");
                return;
            }

            Frm_AddStaff frm = new Frm_AddStaff(staffID: staff.ID, status: EStatus.Modify);
            frm.SaveEvent += Staff_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void Staff_UpdateSaveEvent(Object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            CompanyStaffInfo info = sender as CompanyStaffInfo;
            var deptID = DeptTree.FocusedNode.GetValue("ID");
            //获取焦点行句柄
            //int handle = StaffView.FocusedRowHandle;
            if (info != null)
            {
                //第一个参数指的是FileName，即数据库中的列名
                StaffView.SetFocusedRowCellValue("FName", info.FName);
                StaffView.SetFocusedRowCellValue("Code", info.Code);
                StaffView.SetFocusedRowCellValue("Post", info.Post);
                StaffView.SetFocusedRowCellValue("Wage", info.Wage);
                StaffView.SetFocusedRowCellValue("ProvinceID", info.ProvinceID);
                StaffView.SetFocusedRowCellValue("Graduation", info.Graduation);
            }
            else
            {
                aservice = new AppService();
                StaffGrid.DataSource = aservice.GetStaffByDeptID((Guid)deptID);
            }
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var staff = this.GetChecked<CompanyStaffInfo>(StaffView);
            if (staff.Count <= 0)
            {
                ShowInfo("请勾选需要删除的员工!");
                return;
            }

            //将流写入Guid数组
            var staffID = staff.Select(p => p.ID).ToArray();
            var deptID = DeptTree.FocusedNode.GetValue("ID");

            if (DialogResult.OK == MessageBox.Show("是否删除所选员工?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                AppService aservice = new AppService();
                int count = aservice.DelStaffByChecked((Guid)deptID, staffID);
                StaffGrid.DataSource = aservice.GetStaffByDeptID((Guid)deptID);
                ShowInfo($"成功删除{count}条员工数据!");
            }
        }

        /// <summary>
        /// 指示器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StaffView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        /// <summary>
        /// 表格内容改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StaffView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            AppService aservice = new AppService();
            var focusStaff = StaffView.GetFocusedRow() as CompanyStaffInfo;
            if (e.Column.FieldName == "ProvinceID")
            {
                Object provinceID = StaffView.GetRowCellValue(StaffView.FocusedRowHandle,"ProvinceID");
                aservice.UpdateStaffByID(focusStaff.ID,(Guid)provinceID);
            }
        }
        #endregion

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem11_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            AppService aservice = new AppService();
            if (CompanyTree.Nodes.Count <= 0 || DeptTree.Nodes.Count <= 0)
            {
                ShowInfo("请先选择公司与部门!");
                return;
            }
            //var deptID = DeptTree.FocusedNode.GetValue("ID");
            //var staffs = aservice.GetStaffByDeptID((Guid)deptID);

            var staff = (List<CompanyStaffInfo>)StaffGrid.DataSource;

            Print(staff, true);
        }
        private GridppReport ListReport;
        private void SetPrinter()
        {

            ListReport.Printer.PrinterName = Enumerable.Range(0, ListReport.Utility.GetPrinterCount()).Select(ListReport.Utility.GetPrinterName).FirstOrDefault(p => p == "一号打印机") ?? ListReport.Printer.PrinterName;
        }
        private void Print(List<CompanyStaffInfo> data, bool preview)
        {
            if (data.Count <= 0)
            {
                ShowInfo("无数据!");
                return;
            }
            ListReport = new GridppReport();
            SetPrinter();
            
            ListReport.LoadFromFile(System.AppDomain.CurrentDomain.BaseDirectory + @"Reports\CompanyStaffInfo.grf");
            ListReport.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ListFetchRecord(data));
            //打印预览
            if (preview)
            {
                ListReport.PrintPreview(true);
            }
            else
            {
                ListReport.Print(false);
            }
            
        }

        private Action ListFetchRecord(List<CompanyStaffInfo> data)
        {
            var dept = DeptTree.FocusedNode.GetValue("Name"); 

            return () =>
            {
                ListReport.ControlByName("StaticBox15").AsStaticBox.Text = (string)dept;
                ListReport.ControlByName("StaticBox16").AsStaticBox.Text = "0759-2277092";
                ListReport.ControlByName("StaticBox17").AsStaticBox.Text = "玉天恒";
                ListReport.ControlByName("StaticBox18").AsStaticBox.Text = Convert.ToString(DateTime.Now.ToString("yyyy/MM/dd"));

                BaseXtraForm.FillRecordToReport(ListReport, data.Select((p, i) => new CompanyStaffInfo
                {
                    Num = (i + 1),
                    FName = p.FName,
                    Code = p.Code,
                    Post = p.Post,
                    Wage = p.Wage,
                    Province = p.Province,
                    EnterTime = p.EnterTime,
                    Graduation = p.Graduation,
                }));
            };
        }

        
    }
}
